package com.wangsd.common.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.BaseUtils;
import com.wangsd.web.sys.entity.SysCompany;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class WxpayService {

    private WxPayService wxPayService;

    public WxpayService(SysCompany company, String subMchid, String subAppid) {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(company.getWxAppId()));
        payConfig.setMchId(StringUtils.trimToNull(company.getWxMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(company.getWxMchKey()));
        payConfig.setSubAppId(StringUtils.trimToNull(subAppid));
        payConfig.setSubMchId(StringUtils.trimToNull(subMchid));
        String keyPath = BaseUtils.getPathCertByName(StringUtils.trimToNull(company.getWxKeyPath()));
        payConfig.setKeyPath(keyPath);
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
    }

    private Object send(WxPayUnifiedOrderRequest request, String outTradeNo, String total_fee, String notifyUrl) {
        request.setNonceStr(System.currentTimeMillis() + "");
        request.setBody("商品购买");
        request.setProductId(System.currentTimeMillis()+"");
        request.setSpbillCreateIp("127.0.0.2");
        request.setOutTradeNo(outTradeNo);
        request.setTotalFee(Integer.parseInt(total_fee));
        request.setNotifyUrl(notifyUrl);

        Object result;
        try {
            result = wxPayService.createOrder(request);
        } catch (WxPayException e) {
            throw new BusinessException(e.getReturnMsg());
        }
        return result;
    }
    public JSONObject sendNative(String outTradeNo, String total_fee, String notifyUrl) {
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setTradeType("NATIVE");

        Object result = this.send(request, outTradeNo, total_fee, notifyUrl);
        return JSON.parseObject(JSON.toJSONString(result));
    }

    public JSONObject sendJsApi(String outTradeNo, String total_fee, String notifyUrl, String subOpenid) {
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setTradeType("JSAPI");
        request.setSubOpenid(subOpenid);
        Object result = this.send(request, outTradeNo, total_fee, notifyUrl);
        return JSON.parseObject(JSON.toJSONString(result));
    }
}
